﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Windows.Forms;

namespace FHTZ_analytical_system
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //MessageBox.Show("已找到MT4数据目录，请点击'开始安装'");
            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MetaQuotes\\Terminal\\";
            //MessageBox.Show(path);
            DirectoryInfo dires = new DirectoryInfo(path);
            foreach (DirectoryInfo NextFolder in dires.GetDirectories())
            {
                //MessageBox.Show(NextFolder.Name);
                string mt4Path = NextFolder.FullName;
                if (File.Exists(mt4Path + "\\origin.txt")
                    && Directory.Exists(mt4Path + "\\templates")
                    && Directory.Exists(mt4Path + "\\MQL4\\Indicators"))
                {
                    /*
                    string text = System.IO.File.ReadAllText(path + NextFolder.Name + "\\origin.txt");
                    if (text.EndsWith("方浩投资MT4") || text.EndsWith("MetaTrader 4") || text.EndsWith("MT4"))
                    {
                        //MessageBox.Show(path + NextFolder.Name + "\\");
                        //FilesCopy.CopyDir(".\\installfiles\\", path + NextFolder.Name + "\\");
                        string target_path = path + NextFolder.Name;
                        listView1.Items.Add(new ListViewItem(target_path));
                    }
                    */
                    string text = System.IO.File.ReadAllText(mt4Path + "\\origin.txt");
                    if (text.EndsWith("fanghaotz_MT4"))
                    {
                        string target_path = path + NextFolder.Name;
                        listView1.Items.Add(new ListViewItem(target_path));
                    }
                }
            }
        }

        // 安装
        private void button1_Click(object sender, EventArgs e)
        {
            // string desktop_path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            // string cwd = Application.StartupPath;
            // DirectoryInfo cwdDir = new DirectoryInfo(cwd);
            foreach (ListViewItem item in listView1.Items)
            {
                if (item.Text != "完成")
                {
                    copyFilesTo(item.Text);
                    item.Text = "完成";
                }
            }
        }
        // Helper function
        public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream _FileStream =
                   new System.IO.FileStream(_FileName, System.IO.FileMode.Create,
                                            System.IO.FileAccess.Write);
                // Writes a block of bytes to this stream using data from
                // a byte array.
                _FileStream.Write(_ByteArray, 0, _ByteArray.Length);

                // close file stream
                _FileStream.Close();

                return true;
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}",
                                  _Exception.ToString());
            }
            // error occured, return false
            return false;
        }

        // Helper function
        private void copyFilesTo(string path)
        {
            /*
            var ass = Assembly.GetExecutingAssembly();
            foreach (var file in ass.GetManifestResourceNames())
                Console.WriteLine(file);
            */

            ResourceManager rm = new ResourceManager("FHTZ_analytical_system.Properties.Resources",
                Assembly.GetExecutingAssembly());
            Bitmap fhtzLogo = (Bitmap) rm.GetObject("fhtz_logo");
            fhtzLogo.Save(path + "\\MQL4\\Images\\fhtz_logo.bmp");

            Bitmap fhtzButton1 = (Bitmap)rm.GetObject("button_1");
            fhtzButton1.Save(path + "\\MQL4\\Images\\button_1.bmp");

            Bitmap fhtzButton2 = (Bitmap)rm.GetObject("button_2");
            fhtzButton2.Save(path + "\\MQL4\\Images\\button_2.bmp");

            Bitmap fhtzButton3 = (Bitmap)rm.GetObject("button_3");
            fhtzButton3.Save(path + "\\MQL4\\Images\\button_3.bmp");

            Bitmap fhtzButtonDown1 = (Bitmap)rm.GetObject("button_down_1");
            fhtzButtonDown1.Save(path + "\\MQL4\\Images\\button_down_1.bmp");

            Bitmap fhtzButtonDown2 = (Bitmap)rm.GetObject("button_down_2");
            fhtzButtonDown2.Save(path + "\\MQL4\\Images\\button_down_2.bmp");

            Bitmap fhtzButtonDown3 = (Bitmap)rm.GetObject("button_down_3");
            fhtzButtonDown3.Save(path + "\\MQL4\\Images\\button_down_3.bmp");

            // fhtzLogo.Save("C:\\abc.bmp");
            byte[] fhtzTarget = (byte[]) rm.GetObject("FHTZ_Target");

            Console.WriteLine(fhtzTarget != null);
            bool copied = ByteArrayToFile(path + "\\MQL4\\Indicators\\FHTZ_Target.ex4", fhtzTarget);
            Console.WriteLine(copied);

            byte[] fhtzTA = (byte[])rm.GetObject("FHTZ_Trader_Assist");
            Console.WriteLine(fhtzTarget != null);
            copied = ByteArrayToFile(path + "\\MQL4\\Indicators\\FHTZ_Trader_Assist.ex4", fhtzTA);
            Console.WriteLine(copied);

            byte[] fhtzBarrier = (byte[])rm.GetObject("FHTZ_Barrier");
            Console.WriteLine(fhtzBarrier != null);
            copied = ByteArrayToFile(path + "\\MQL4\\Indicators\\fhtzBarrier.ex4", fhtzBarrier);
            Console.WriteLine(copied);

            byte[] fhtzTAPro = (byte[])rm.GetObject("FHTZ_Trader_Assist_Pro");
            Console.WriteLine(fhtzTAPro != null);
            copied = ByteArrayToFile(path + "\\MQL4\\Experts\\FHTZ_Trader_Assist_Pro.ex4", fhtzTAPro);
            Console.WriteLine(copied);

            byte[] fhtzProTpl = (byte[])rm.GetObject("方浩分析系统_尊享版");
            Console.WriteLine(fhtzProTpl != null);
            copied = ByteArrayToFile(path + "\\templates\\方浩分析系统_尊享版.tpl", fhtzProTpl);
            Console.WriteLine(copied);

            byte[] fhtzAlert = (byte[])rm.GetObject("FHTZ_Alert");
            copied = ByteArrayToFile(path + "\\MQL4\\Indicators\\FHTZ_Alert.ex4", fhtzAlert);
            Console.WriteLine(copied);

            byte[] fhtzTradingTime = (byte[])rm.GetObject("FHTZ_TradingTimes");
            copied = ByteArrayToFile(path + "\\MQL4\\Indicators\\FHTZ_TradingTimes.ex4", fhtzTradingTime);
            Console.WriteLine(copied);

            byte[] fhtzCloseScript = (byte[])rm.GetObject("双击平仓脚本");
            copied = ByteArrayToFile(path + "\\MQL4\\Scripts\\双击平仓脚本.ex4", fhtzCloseScript);
            Console.WriteLine(copied);

            byte[] fhtzSlTp = (byte[])rm.GetObject("一次性设止损止盈脚本");
            copied = ByteArrayToFile(path + "\\MQL4\\Scripts\\一次性设止损止盈脚本.ex4", fhtzSlTp);
            Console.WriteLine(copied);
            /*
            string cwd = Application.StartupPath;
            DirectoryInfo cwdDir = new DirectoryInfo(cwd);
            foreach (FileInfo file in cwdDir.GetFiles())
            {
                if (file.Name.EndsWith(".tpl"))
                {
                    Console.WriteLine("TPL FILE:" + file.Name);
                    Console.WriteLine("Write a template");
                    // File.Copy(file.FullName, targetFile, true);      
                    file.CopyTo(path + "\\templates\\" + file.Name, true);
                }
                else if (file.Name.EndsWith(".ex4"))
                {
                    Console.WriteLine("EX 4 File:" + file.Name);
                    File.Copy(file.FullName, path + "\\MQL4\\Indicators\\" + file.Name, true);
                }
                else if (file.Name.EndsWith(".bmp"))
                {
                    Console.WriteLine("Images File:" + file.Name);
                    if (!Directory.Exists(path + "\\MQL4\\Images"))
                    {
                        Directory.CreateDirectory(path + "\\MQL4\\Images");
                    }
                    File.Copy(file.FullName,path + "\\MQL4\\Images\\" + file.Name, true);
                }
             }
            */
        }
        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {

        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void listView1_SelectedIndexChanged_1(object sender, EventArgs e)
        {

        }

        // 手动添加路径
        private void button1_Click_1(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                String mt4Path = folderBrowserDialog1.SelectedPath;
                if (Directory.Exists(mt4Path + "\\templates")
                    && Directory.Exists(mt4Path + "\\MQL4\\Indicators"))
                {
                    listView1.Items.Add(new ListViewItem(mt4Path));
                } else
                {
                    MessageBox.Show("请输入正确的MT4数据文件夹");
                }
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            int num = listView1.Items.Count;
            if (num >= 1)
            {
                listView1.Items.RemoveAt(num - 1);
            }
        }
    }
}
